<?php
namespace ucenter\client\controllers;

use Yii;
use services\ucenter\UserService;
use heihei\rest\Controller;

use heihei\helpers\HttpClientHelper;
use heihei\libs\weixin\MP as WeixinMP;


/**
 * 注册控制器
 */
class RegisterController extends Controller
{
    /**
     * 注册
     *
     * @return string
     */
    public function actionIndex()
    {
        
    }

    /**
     * 微信小程序
     *
     * @return string
     */
    public function actionWxMiniProgram()
    {
        $request = Yii::$app->getRequest();
        $sessionKey = $request->post('session_key');
        if(!$sessionKey){
            return $this->fail("session_key必传！");
        }

        $iv = $request->post('iv');
        if(!$iv){
            return $this->fail("iv必传！");
        }

        $encryptedData = $request->post('encrypted_data');
        if(!$encryptedData){
            return $this->fail("encrypted_data必传！");
        }
        
        /*$wxmp = new WeixinMP([
            'appid' => 'wx1a4b112440df7c69',
            'secret' => 'f520694e80939ac59c4fedcd34f02ce0'
        ]);*/

        $wxmp = new WeixinMP([
            'appid' => 'wxe84d1fab98fba93c',
            'secret' => 'f913de53c6e12ce215d962bd54670a0b'
        ]);

        
        $bizDataCrypt = $wxmp->get('BizDataCrypt', ['sessionKey' => $sessionKey]);
        $decryptResult = $bizDataCrypt->decryptData($encryptedData, $iv, $decryptData);
        if($decryptResult != 0){
            return $this->fail('解密失败！');
        }
        $decryptData = json_decode($decryptData, true);
        $mobile = $decryptData['purePhoneNumber'];
        $regData = ['mobile' => $mobile];
        $result = UserService::register($regData);
        var_dump($result);
        return $decryptData;
    }
}
